/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="flow-statistics">
    <div class="flow-channelization tuxing-left" ref="tuxingLeft">
      <div class="flow-statistic-map">
          <channelization-flow-statistic
            :AgentId="AgentId"
            :resizeMap="resizeFlowChannelization"
            :phasesStatisticsList="phasesStatistics"
            :bcgColor="handleCongestionindexColor(intesStatistics.congestionindex)"
            :customText="intesStatistics.congestionindex"
            textFontSize="50"  />
      </div>
      <div class="intes-statistics-block">
        <span>{{$t('edge.flowstatistics.totalflow')}}: {{intesStatistics.totalflow}}</span>
        <span>{{$t('edge.flowstatistics.averageflow')}}: {{intesStatistics.averageflow}}</span>
        <span>{{$t('edge.flowstatistics.avergreenusage')}}: <span>{{intesStatistics.greenusage}}%</span></span>
        <span>{{$t('edge.flowstatistics.aversaturation')}}: <span>{{intesStatistics.saturation}}%</span></span>
      </div>
    </div>
    <div class="phase-flow-table tuxing-right" ref="tuxingRight">
        <el-table
        :data="phasesStatistics"
        style="width: 100%"
        :height="600">
        <el-table-column
          align="center"
          :label="$t('edge.flowstatistics.phase')">
          <template slot-scope="scope">
            <div class="phase-dir">
              <xdr-dir-selector Width="40px" Height="40px" :showlist="getShowlist(scope.row.direction)" :roadDirection="roadDirection"></xdr-dir-selector>
            </div>
            <div>{{$t('edge.flowstatistics.phase') + scope.row.phaseno}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="phasestatistics.totalflow"
          :label="$t('edge.flowstatistics.flow')">
        </el-table-column>
        <el-table-column
          align="center"
          prop="phasestatistics.greenusage"
          :label="$t('edge.flowstatistics.greenusage')">
          <template slot-scope="scope">
            <div v-if="scope.row.phasestatistics.greenusage !== undefined">{{scope.row.phasestatistics.greenusage + '%'}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="phasestatistics.saturation"
          :label="$t('edge.flowstatistics.saturation')">
          <template slot-scope="scope">
            <div v-if="scope.row.phasestatistics.saturation !== undefined">{{scope.row.phasestatistics.saturation + '%'}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('edge.flowstatistics.congestionindex')">
          <template slot-scope="scope">
            <div :style="{'color': handleCongestionindexColor(scope.row.phasestatistics.congestionindex)}">{{scope.row.phasestatistics.congestionindex}}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getMessageByCode } from '../../utils/responseMessage'
import { getPhasesStatistics, getIntesStatistics } from '@/api/cross'
import { uploadSingleTscParam } from '@/api/param'
export default {
  name: 'flow-statistics',
  computed: {
    ...mapState({
      curOpenatcAgentid: state => state.globalParam.curOpenatcAgentid,
      curHomePage: state => state.globalParam.curHomePage,
      roadDirection: state => state.globalParam.roadDirection
    })
  },
  props: {
    AgentId: {
      type: String,
      default: '0'
    }
  },
  watch: {
    curHomePage: {
      handler: function (newval, oldval) {
        if (oldval !== 'Flowstatistics' && newval === 'Flowstatistics') {
          this.resizeFlowChannelization = true
          // this.getIntesStatistics()
          // this.getPhasesStatistics()
          this.handleAllStatisticsTimer()
        }
      }
    }
  },
  data () {
    return {
      phasesStatistics: [],
      intesStatistics: {
        totalflow: 0,
        averageflow: 0,
        saturation: 0,
        congestionindex: '',
        greenusage: 0
      },
      phaseList: [],
      resizeFlowChannelization: false, // 是否重载底图大小
      colorMap: new Map([['A', '#009900'], ['B', '#00FF00'], ['C', '#FFFF00'], ['D', '#FF9900'], ['E', '#FF0000'], ['F', '#990000']]),
      commonHeight: undefined // 左右侧面板的高度值
    }
  },
  methods: {
    getPhasesStatistics () {
      return new Promise((resolve, reject) => {
        getPhasesStatistics(this.AgentId).then(data => {
          if (!data.data.success) {
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
            // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                this.$message.error(parrenterror + ',' + childerror)
              }
            } else {
              this.$message.error(parrenterror)
            }
            return
          }
          this.phasesStatistics = data.data.data.phasesstatisticsList[0]
          for (let i = 0; i < this.phasesStatistics.length; i++) {
            this.phasesStatistics[i].direction = this.phaseList.filter(phase => phase.id === this.phasesStatistics[i].phaseno)[0].direction
          }
          resolve(this.phasesStatistics)
        })
      })
    },
    getIntesStatistics () {
      return new Promise((resolve, reject) => {
        getIntesStatistics(this.AgentId).then(data => {
          if (!data.data.success) {
            let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
            if (data.data.data) {
            // 子类型错误
              let childErrorCode = data.data.data.errorCode
              if (childErrorCode) {
                let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
                this.$message.error(parrenterror + ',' + childerror)
              }
            } else {
              this.$message.error(parrenterror)
            }
            return
          }
          if (data.data.data.intestatistics && data.data.data.intestatistics.length > 0) {
            this.intesStatistics = data.data.data.intestatistics[0]
          }
          resolve(this.intesStatistics)
        })
      })
    },
    handleCongestionindexColor (congestionindex) {
      if (!congestionindex) return
      let color = this.colorMap.get(congestionindex) || 'rgba(94, 90, 90, 0.8)'
      return color
    },
    handleColor (saturation, greenusage) {
      if (saturation >= 0 && saturation <= 30 && greenusage < 80) {
        return this.colorMap('A')
      }
      if (saturation > 30 && saturation <= 70 && greenusage < 80) {
        return this.colorMap('B')
      }
      if (saturation > 70 && greenusage < 80) {
        return this.colorMap('C')
      }
      if (saturation > 70 && greenusage >= 80) {
        return this.colorMap('D')
      }
      if (saturation > 30 && saturation <= 70 && greenusage >= 80) {
        return this.colorMap('E')
      }
      if (saturation >= 0 && saturation <= 30 && greenusage >= 80) {
        return this.colorMap('F')
      }
    },
    getShowlist (direction) {
      if (!direction) return []
      return direction.map(dir => {
        return {
          id: dir,
          color: '#606266'
        }
      })
    },
    getPhase () {
      return new Promise((resolve, reject) => {
        uploadSingleTscParam('phase').then(data => {
          let res = data.data
          if (!res.success) {
            if (res.code === '4003') {
              this.$message.error(this.$t('edge.errorTip.devicenotonline'))
              return
            }
            this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
            return
          }
          this.phaseList = res.data.data.phaseList
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    handleAllStatisticsTimer () {
      this.clearAllStatisticsTimer()
      this.getPhasesStatistics()
      this.getIntesStatistics()
      this.allStatisticsTimerTimer = setInterval(() => {
        this.getPhasesStatistics()
        this.getIntesStatistics()
      }, 300000)
    },
    clearAllStatisticsTimer () {
      if (this.allStatisticsTimerTimer !== null) {
        clearInterval(this.allStatisticsTimerTimer) // 清除定时器
        this.allStatisticsTimerTimer = null
      }
    }
  },
  created () {
  },
  async mounted () {
    await this.getPhase()
    this.handleAllStatisticsTimer()
  },
  destroyed () {
    this.clearAllStatisticsTimer()
  },
  updated () {
    if (this.$refs.tuxingLeft.offsetHeight !== this.commonHeight) {
      // 根据左侧面板动态变化的高度，同步更新右侧面板高度
      this.commonHeight = this.$refs.tuxingLeft.offsetHeight
      this.$refs.tuxingRight.style.height = this.commonHeight + 'px'
    }
  }
}
</script>

<style lang="css" rel="stylesheet/scss" scoped>
.phase-dir {
  position: relative;
  background: rgb(217, 236, 255);
  width: 42PX;
  height: 40PX;
  margin: 0 auto;
}
</style>
